package botoseis.mainGui.database;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.LookupPaintScale;
import org.jfree.chart.renderer.xy.XYBlockRenderer;
import org.jfree.chart.title.PaintScaleLegend;
import org.jfree.data.xy.DefaultXYZDataset;
import org.jfree.data.xy.XYZDataset;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.RefineryUtilities;
/**
 *
 * @author wogonowski
 */
public class DBMap extends javax.swing.JFrame {

    /**
     * Creates new form Map
     */
    public DBMap() {
        initComponents();
        JPanel chartPanel = createDemoPanel();
        chartPanel.setPreferredSize(new Dimension(750,600));
        chartPanel.setPreferredSize(new java.awt.Dimension(800, 800));
        setContentPane(chartPanel);
    }
    public static JPanel createDemoPanel() {
        return new ChartPanel(createChart(createDataset()));
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(800, 800));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 779, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 704, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

     /**
     * Creates a  chart.
     * 
     * @param dataset  the dataset.
     * 
     * @return A  chart.
     */
    private static JFreeChart createChart(XYZDataset dataset) {
        NumberAxis xAxis = new NumberAxis("X");
        xAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        xAxis.setLowerMargin(10.0);
        xAxis.setUpperMargin(0.0);
        xAxis.setAutoRange(true);
        
        NumberAxis yAxis = new NumberAxis("Y");
        yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        yAxis.setLowerMargin(0.0);
        yAxis.setUpperMargin(0.0);
        yAxis.setAutoRange(true);
        
        XYBlockRenderer renderer = new XYBlockRenderer();

        
        
      LookupPaintScale ps = new LookupPaintScale(getMinV(),getMaxV(), Color.GRAY);
    
      int red = 0;
      int blue = 0;
      int green = 0;
      float valInc = (getMaxV()-getMinV())/(1151f);
      float value = getMinV()-valInc;
      red = 0;
      blue = 0;
      green = 0;
      for (blue = 127; blue < 256; blue++) {
         Color c = new Color(red, green, blue);
         ps.add(value = value + valInc, c);
  
      }
      red = 0;
      blue = 255;
      green = 0;
      for (green = 0; green < 256; green++) {
         Color c = new Color(red, green, blue);
         ps.add(value = value + valInc, c);
    
      }
      red = 0;
      blue = 255;
      green = 255;
      for (blue = 255; blue > 0; blue--) {
         Color c = new Color(red, green, blue);
         ps.add(value = value + valInc, c);
 
      }
      red = 0;
      green = 255;
      blue = 0;
      for (red = 0; red < 256; red++) {
         Color c = new Color(red, green, blue);
         ps.add(value = value + valInc, c);

      }
      red = 255;
      green = 255;
      blue = 0;
      for (green = 255; green > 0; green--) {
         Color c = new Color(red, green, blue);
         ps.add(value = value + valInc, c);

      }
  
      ps.add(value = getMaxV(),(new Color(127,0,0)));


         renderer.setBlockHeight(6);
         renderer.setBlockWidth(6);
         
         //code adding paints to paintScale
        renderer.setPaintScale(ps);
        //NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    
        
        XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
        //plot.setBackgroundPaint(Color.lightGray);

        plot.setRangeGridlinePaint(Color.lightGray);
        JFreeChart chart = new JFreeChart("Map of database attribute", plot);

         chart.removeLegend();
        NumberAxis scaleAxis = new NumberAxis("Scale");
        scaleAxis.setAxisLinePaint(Color.gray);
        scaleAxis.setTickMarkPaint(Color.gray);
        scaleAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 7));
       // scaleAxis.setRange(min, max);
        PaintScaleLegend legend = new PaintScaleLegend(ps,scaleAxis);
        legend.setAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        legend.setAxisOffset(5.0);
        legend.setMargin(new RectangleInsets(5, 5, 5, 5));
        legend.setFrame(new BlockBorder(Color.black));
        legend.setPadding(new RectangleInsets(10, 10, 10, 10));
        legend.setStripWidth(10);
        legend.setPosition(RectangleEdge.RIGHT);
       // legend.setBackgroundPaint(new Color(120, 120, 180));
        chart.addSubtitle(legend);
        //chart.setBackgroundPaint(new Color(180, 180, 250));
         
         ValueAxis rangeAxis = plot.getRangeAxis();
         ValueAxis domainAxis = plot.getDomainAxis();
         
         double upperY=rangeAxis.getUpperBound();
         double upperX=domainAxis.getUpperBound();
         domainAxis.setRange(getMinX(),upperX);
         rangeAxis.setRange(getMinY(), upperY);
        return chart;
    }
      
    /**
     * Creates a sample dataset.
     */
    private static XYZDataset createDataset() {
        
        DefaultXYZDataset dataset = new DefaultXYZDataset();
        
             Connection con=null;
             ResultSet rs = null;
             PreparedStatement pst = null;  
             con=DBConnect.ConnectDb();
             try {  
                   String queryPr ="SELECT  COUNT(*) as nrows FROM ATTRXYZ ";
                   pst=con.prepareStatement(queryPr);
                   rs = pst.executeQuery();
                   rs.next();
                   int size=rs.getInt("nrows");
                   double[][] data = new double[3][size*3];
                   String queryP ="SELECT  X1,Y1,Z1 FROM ATTRXYZ ";
                   pst=con.prepareStatement(queryP);
                   rs = pst.executeQuery();
                   int i=0;
                while (rs.next()) { 

                data[0][i] = rs.getDouble("X1");

                data[1][i] = rs.getDouble("Y1"); 

                data[2][i] = rs.getDouble("Z1");      
                    i=i+1;
                  //JOptionPane.showMessageDialog(null,dataset);
                }        
                            dataset.addSeries("A",data);
            } catch (Exception e) {  
            System.out.println("Retrieving Data Fail");  
            } finally {
                 try {
                 rs.close();
                 pst.close();
                //con.close();
                }
                 catch (Exception e) {
                 }
             }            

        return dataset;
    }
    
    public static float getMinV(){
    
             Connection con=null;
             ResultSet rs = null;
             PreparedStatement pst = null;  
             con=DBConnect.ConnectDb();
                     float min = 0;
             try {  
                   String queryMinMax ="SELECT MIN(Z1) AS min FROM ATTRXYZ";
                   pst=con.prepareStatement(queryMinMax);
                   rs = pst.executeQuery();
                   rs.next();
                   min=rs.getFloat("min");

            } catch (Exception e) {  
            System.out.println("Retrieving Data Fail");  
            } finally {
                 try {
                 rs.close();
                 pst.close();
                //con.close();
                }
                 catch (Exception e) {
                 }
              return min;
             }            
}
      public static float getMaxV(){
    
             Connection con=null;
             ResultSet rs = null;
             PreparedStatement pst = null;  
             con=DBConnect.ConnectDb();
              float max=0;
             try {  
                   String queryMinMax ="SELECT MAX(Z1) AS max FROM ATTRXYZ";
                   pst=con.prepareStatement(queryMinMax);
                   rs = pst.executeQuery();
                   rs.next();
                   max=rs.getFloat("max");
            } catch (Exception e) {  
            System.out.println("Retrieving Data Fail");  
            } finally {
                 try {
                 rs.close();
                 pst.close();
                //con.close();
                }
                 catch (Exception e) {
                 }
             }            
             return max;
}  
          public static double getMinX(){
    
             Connection con=null;
             ResultSet rs = null;
             PreparedStatement pst = null;  
             con=DBConnect.ConnectDb();
             double minX = 0;
             try {  
                   String queryMinMax ="SELECT MIN(X1) AS min FROM ATTRXYZ";
                   pst=con.prepareStatement(queryMinMax);
                   rs = pst.executeQuery();
                   rs.next();
                   minX=rs.getDouble("min");


            } catch (Exception e) {  
            System.out.println("Retrieving Data Fail");  
            } finally {
                 try {
                 rs.close();
                 pst.close();
                //con.close();
                }
                 catch (Exception e) {
                 }
                 return minX;
             }            
}
          
            public static double getMinY(){
    
             Connection con=null;
             ResultSet rs = null;
             PreparedStatement pst = null;  
             con=DBConnect.ConnectDb();
             double minY = 0;

             try {  
                   String queryMinMax ="SELECT MIN(Y1) AS min FROM ATTRXYZ";
                   pst=con.prepareStatement(queryMinMax);
                   rs = pst.executeQuery();
                   rs.next();
                   minY=rs.getDouble("min");
            } catch (Exception e) {  
            System.out.println("Retrieving Data Fail");  
            } finally {
                 try {
                 rs.close();
                 pst.close();
                //con.close();
                }
                 catch (Exception e) {
                 }
                 return minY;
             }            
}      
   
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DBMap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DBMap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DBMap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DBMap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
        DBMap map = new DBMap();
        map.pack();
        RefineryUtilities.centerFrameOnScreen(map);
        map.setVisible(true);
         
            }
        });
    }
    // Variables declaration - do not modify
    // End of variables declaration
}
